<template>
  <div class="table-demo">
    <div class="example-section">
      <h3 class="section-title">基础数据表格</h3>
      <p class="section-description">展示基础的数据表格功能，包括排序、筛选、分页等</p>

      <div class="table-container">
        <div class="table-header">
          <div class="table-title">用户列表</div>
          <div class="table-actions">
            <a-input-search
              v-model:value="searchText"
              placeholder="搜索用户"
              style="width: 200px"
              @search="handleSearch"
            />
            <a-button type="primary" @click="handleAdd">
              <plus-outlined />
              新增用户
            </a-button>
          </div>
        </div>

        <a-table
          :columns="userColumns"
          :data-source="filteredUsers"
          :pagination="pagination"
          :loading="loading"
          row-key="id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'avatar'">
              <a-avatar :src="record.avatar" :alt="record.name">
                {{ record.name.charAt(0) }}
              </a-avatar>
            </template>

            <template v-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusText(record.status) }}
              </a-tag>
            </template>

            <template v-if="column.key === 'balance'">
              <span class="balance-text">¥{{ formatNumber(record.balance) }}</span>
            </template>

            <template v-if="column.key === 'action'">
              <a-space>
                <a-button type="link" size="small" @click="handleEdit(record)">
                  编辑
                </a-button>
                <a-button type="link" size="small" @click="handleView(record)">
                  查看
                </a-button>
                <a-popconfirm
                  title="确定要删除这个用户吗？"
                  @confirm="handleDelete(record)"
                >
                  <a-button type="link" size="small" danger>
                    删除
                  </a-button>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <div class="example-section">
      <h3 class="section-title">高级数据表格</h3>
      <p class="section-description">包含更多高级功能的数据表格，如行选择、批量操作等</p>

      <div class="table-container">
        <div class="table-header">
          <div class="table-title">订单管理</div>
          <div class="table-actions">
            <a-select
              v-model:value="statusFilter"
              placeholder="筛选状态"
              style="width: 120px"
              @change="handleStatusFilter"
            >
              <a-select-option value="">全部</a-select-option>
              <a-select-option value="pending">待处理</a-select-option>
              <a-select-option value="processing">处理中</a-select-option>
              <a-select-option value="completed">已完成</a-select-option>
              <a-select-option value="cancelled">已取消</a-select-option>
            </a-select>
            <a-range-picker
              v-model:value="dateRange"
              @change="handleDateFilter"
            />
          </div>
        </div>

        <div class="batch-actions" v-if="selectedRowKeys.length > 0">
          <span class="selected-info">已选择 {{ selectedRowKeys.length }} 项</span>
          <a-space>
            <a-button @click="handleBatchProcess">批量处理</a-button>
            <a-button @click="handleBatchExport">批量导出</a-button>
            <a-button danger @click="handleBatchDelete">批量删除</a-button>
          </a-space>
        </div>

        <a-table
          :columns="orderColumns"
          :data-source="filteredOrders"
          :pagination="orderPagination"
          :loading="orderLoading"
          :row-selection="rowSelection"
          row-key="id"
          @change="handleOrderTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'orderNo'">
              <a-button type="link" @click="handleViewOrder(record)">
                {{ record.orderNo }}
              </a-button>
            </template>

            <template v-if="column.key === 'status'">
              <a-tag :color="getOrderStatusColor(record.status)">
                {{ getOrderStatusText(record.status) }}
              </a-tag>
            </template>

            <template v-if="column.key === 'amount'">
              <span class="amount-text">¥{{ formatNumber(record.amount) }}</span>
            </template>

            <template v-if="column.key === 'createTime'">
              {{ formatDate(record.createTime) }}
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <div class="example-section">
      <h3 class="section-title">组件代码示例</h3>
      <p class="section-description">数据表格组件的使用方法</p>

      <a-collapse>
        <a-collapse-panel key="1" header="基础表格代码">
          <pre class="code-block"><code>&lt;template&gt;
  &lt;a-table
    :columns="columns"
    :data-source="dataSource"
    :pagination="pagination"
    row-key="id"
  &gt;
    &lt;template #bodyCell="{ column, record }"&gt;
      &lt;template v-if="column.key === 'status'"&gt;
        &lt;a-tag :color="getStatusColor(record.status)"&gt;
          {{ getStatusText(record.status) }}
        &lt;/a-tag&gt;
      &lt;/template&gt;
    &lt;/template&gt;
  &lt;/a-table&gt;
&lt;/template&gt;</code></pre>
        </a-collapse-panel>

        <a-collapse-panel key="2" header="高级表格代码">
          <pre class="code-block"><code>&lt;template&gt;
  &lt;a-table
    :columns="columns"
    :data-source="dataSource"
    :pagination="pagination"
    :row-selection="rowSelection"
    row-key="id"
    @change="handleTableChange"
  &gt;
    &lt;!-- 自定义列内容 --&gt;
  &lt;/a-table&gt;
&lt;/template&gt;

&lt;script setup&gt;
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: onSelectChange,
}
&lt;/script&gt;</code></pre>
        </a-collapse-panel>
      </a-collapse>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import type { TableColumnsType } from 'ant-design-vue'

// 用户表格数据
const loading = ref(false)
const searchText = ref('')
const users = ref([
  {
    id: 1,
    name: '张三',
    email: 'zhangsan@example.com',
    phone: '13800138001',
    status: 'active',
    balance: 15800,
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=1',
    createTime: '2024-01-15'
  },
  {
    id: 2,
    name: '李四',
    email: 'lisi@example.com',
    phone: '13800138002',
    status: 'inactive',
    balance: 8900,
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=2',
    createTime: '2024-01-20'
  },
  {
    id: 3,
    name: '王五',
    email: 'wangwu@example.com',
    phone: '13800138003',
    status: 'active',
    balance: 25600,
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=3',
    createTime: '2024-02-01'
  },
  {
    id: 4,
    name: '赵六',
    email: 'zhaoliu@example.com',
    phone: '13800138004',
    status: 'pending',
    balance: 3200,
    avatar: 'https://api.dicebear.com/7.x/avataaars/svg?seed=4',
    createTime: '2024-02-10'
  }
])

const userColumns: TableColumnsType = [
  {
    title: '头像',
    key: 'avatar',
    width: 80,
  },
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
    sorter: (a, b) => a.name.localeCompare(b.name),
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email',
  },
  {
    title: '手机号',
    dataIndex: 'phone',
    key: 'phone',
  },
  {
    title: '状态',
    key: 'status',
    filters: [
      { text: '活跃', value: 'active' },
      { text: '非活跃', value: 'inactive' },
      { text: '待审核', value: 'pending' },
    ],
    onFilter: (value, record) => record.status === value,
  },
  {
    title: '余额',
    key: 'balance',
    sorter: (a, b) => a.balance - b.balance,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
]

const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number, range: [number, number]) =>
    `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
})

// 订单表格数据
const orderLoading = ref(false)
const statusFilter = ref('')
const dateRange = ref()
const selectedRowKeys = ref<number[]>([])

const orders = ref([
  {
    id: 1,
    orderNo: 'ORD202401001',
    customerName: '张三',
    amount: 1580,
    status: 'completed',
    createTime: '2024-01-15 10:30:00'
  },
  {
    id: 2,
    orderNo: 'ORD202401002',
    customerName: '李四',
    amount: 2890,
    status: 'processing',
    createTime: '2024-01-16 14:20:00'
  },
  {
    id: 3,
    orderNo: 'ORD202401003',
    customerName: '王五',
    amount: 5600,
    status: 'pending',
    createTime: '2024-01-17 09:15:00'
  },
  {
    id: 4,
    orderNo: 'ORD202401004',
    customerName: '赵六',
    amount: 890,
    status: 'cancelled',
    createTime: '2024-01-18 16:45:00'
  }
])

const orderColumns: TableColumnsType = [
  {
    title: '订单号',
    key: 'orderNo',
  },
  {
    title: '客户姓名',
    dataIndex: 'customerName',
    key: 'customerName',
  },
  {
    title: '金额',
    key: 'amount',
    sorter: (a, b) => a.amount - b.amount,
  },
  {
    title: '状态',
    key: 'status',
  },
  {
    title: '创建时间',
    key: 'createTime',
    sorter: (a, b) => new Date(a.createTime).getTime() - new Date(b.createTime).getTime(),
  },
]

const orderPagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
})

// 计算属性
const filteredUsers = computed(() => {
  if (!searchText.value) return users.value
  return users.value.filter(user =>
    user.name.includes(searchText.value) ||
    user.email.includes(searchText.value) ||
    user.phone.includes(searchText.value)
  )
})

const filteredOrders = computed(() => {
  let result = orders.value

  if (statusFilter.value) {
    result = result.filter(order => order.status === statusFilter.value)
  }

  return result
})

const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: number[]) => {
    selectedRowKeys.value = keys
  },
}))

// 方法
const formatNumber = (num: number): string => {
  return num.toLocaleString('zh-CN')
}

const formatDate = (dateStr: string): string => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

const getStatusColor = (status: string): string => {
  const colors = {
    active: 'success',
    inactive: 'default',
    pending: 'warning'
  }
  return colors[status as keyof typeof colors] || 'default'
}

const getStatusText = (status: string): string => {
  const texts = {
    active: '活跃',
    inactive: '非活跃',
    pending: '待审核'
  }
  return texts[status as keyof typeof texts] || status
}

const getOrderStatusColor = (status: string): string => {
  const colors = {
    pending: 'warning',
    processing: 'processing',
    completed: 'success',
    cancelled: 'error'
  }
  return colors[status as keyof typeof colors] || 'default'
}

const getOrderStatusText = (status: string): string => {
  const texts = {
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return texts[status as keyof typeof texts] || status
}

// 事件处理
const handleSearch = (value: string) => {
  console.log('搜索:', value)
}

const handleAdd = () => {
  console.log('新增用户')
}

const handleEdit = (record: any) => {
  console.log('编辑用户:', record)
}

const handleView = (record: any) => {
  console.log('查看用户:', record)
}

const handleDelete = (record: any) => {
  console.log('删除用户:', record)
}

const handleTableChange = (pag: any, filters: any, sorter: any) => {
  console.log('表格变化:', { pag, filters, sorter })
}

const handleStatusFilter = (value: string) => {
  console.log('状态筛选:', value)
}

const handleDateFilter = (dates: any) => {
  console.log('日期筛选:', dates)
}

const handleBatchProcess = () => {
  console.log('批量处理:', selectedRowKeys.value)
}

const handleBatchExport = () => {
  console.log('批量导出:', selectedRowKeys.value)
}

const handleBatchDelete = () => {
  console.log('批量删除:', selectedRowKeys.value)
}

const handleViewOrder = (record: any) => {
  console.log('查看订单:', record)
}

const handleOrderTableChange = (pag: any, filters: any, sorter: any) => {
  console.log('订单表格变化:', { pag, filters, sorter })
}

onMounted(() => {
  pagination.value.total = users.value.length
  orderPagination.value.total = orders.value.length
})
</script>

<style scoped>
.table-demo {
  max-width: 1200px;
  margin: 0 auto;
}

.example-section {
  margin-bottom: 48px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #262626;
  margin: 0 0 8px 0;
}

.section-description {
  font-size: 14px;
  color: #8c8c8c;
  margin: 0 0 24px 0;
  line-height: 1.6;
}

.table-container {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-title {
  font-size: 18px;
  font-weight: 600;
  color: #262626;
}

.table-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.batch-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f0f8ff;
  border: 1px solid #d6e4ff;
  border-radius: 6px;
  margin-bottom: 16px;
}

.selected-info {
  font-size: 14px;
  color: #1890ff;
  font-weight: 500;
}

.balance-text,
.amount-text {
  font-weight: 600;
  color: #52c41a;
}

.code-block {
  background: #f6f8fa;
  border: 1px solid #e1e4e8;
  border-radius: 6px;
  padding: 16px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 13px;
  line-height: 1.45;
  overflow-x: auto;
  margin: 0;
}

.code-block code {
  background: none;
  padding: 0;
  font-size: inherit;
  color: #24292e;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .table-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .table-actions {
    flex-wrap: wrap;
  }

  .batch-actions {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .table-container {
    padding: 16px;
  }
}
</style>